angular.module('starter.controllers', [])
    //.constant('serverHost', 'http://api.peizi.me/')
    .constant('serverHost', 'http://192.168.1.105:84/')
    // .constant('newServerHost', 'http://napi.peizi.me/')
    .constant('newServerHost', 'http://192.168.1.105:83/')
    .controller('DashCtrl', function ($scope, $rootScope, $interval, $state, WMP, productList, Local) {
        $scope.$on('$ionicView.enter', function (scopes, states) {
            // if(states.fromCache && states.stateName == "tab.dash"){
            console.log("refreshing Dash");
            //$scope.GetDoublePie();
            // }
        });

        var getCategoryIdByCode = function (categoryCode) {
            var ret = 0;
            switch (categoryCode) {
                case 'wd':
                    ret = 1;
                    break;
                case 'yhlc':
                    ret = 2;
                    break;
                case 'zc' :
                    ret = 3;
                    break;
            }
            return ret;
        }

        $scope.toDetail = function (code, category) {
            Local.setItem("select-productId", code);
            Local.setItem("select-productType", getCategoryIdByCode(category));
            console.log(getCategoryIdByCode(category));
            return true;
        }

        $scope.load = function () {//图片轮播
            $interval(function () {
                i++;
                if (i > 2) {
                    i = 0;
                }
                $scope.imgsrc = ImageArray[i];
                // console.log($scope.imgsrc);
            }, 1000);
            $scope.getListproductList();
        }

        $scope.all = "all";
        $scope.zc = "zc";
        $scope.wd = "wd";
        $scope.yhlc = "yhlc";
        $scope.sjb = "sjb";
        $rootScope.boolwd = true;
        $rootScope.boolzc = true;
        $rootScope.boolyhlc = true;
        $rootScope.boolsjb = true;
        $scope.imgsrc = "img/index.jpg";
        var ImageArray = new Array(3);
        ImageArray[0] = "img/index.jpg";
        ImageArray[1] = "img/index.jpg";
        ImageArray[2] = "img/index.jpg";
        var i = 0;
        //点击标签 首页 众筹 网贷 银行理财 随机报
        $scope.showDV = function ($scope) {
            switch ($scope) {
                case "zc":
                    $rootScope.stylezc = {'background-color': '#F07C2B', "color": "white"};
                    $rootScope.stylewd = {'background-color': ''};
                    $rootScope.styleyhlc = {'background-color': ''};
                    $rootScope.stylesjb = {'background-color': ''};
                    $rootScope.styleall = {'background-color': '', "color": "#F07C2B"};

                    $rootScope.boolzc = true;
                    $rootScope.boolwd = false;
                    $rootScope.boolyhlc = false;
                    $rootScope.boolsjb = false;
                    break;
                case "wd":
                    $rootScope.stylewd = {'background-color': '#F07C2B', "color": "white"};
                    $rootScope.stylezc = {'background-color': ''};
                    $rootScope.styleyhlc = {'background-color': ''};
                    $rootScope.stylesjb = {'background-color': ''};
                    $rootScope.styleall = {'background-color': '', "color": "#F07C2B"};
                    $rootScope.boolwd = true;
                    $rootScope.boolzc = false;
                    $rootScope.boolyhlc = false;
                    $rootScope.boolsjb = false;
                    break;
                case "yhlc":
                    $rootScope.styleyhlc = {'background-color': '#F07C2B', "color": "white"};
                    $rootScope.stylezc = {'background-color': ''};
                    $rootScope.stylewd = {'background-color': ''};
                    $rootScope.stylesjb = {'background-color': ''};
                    $rootScope.styleall = {'background-color': '', "color": "#F07C2B"};
                    $rootScope.boolyhlc = true;
                    $rootScope.boolwd = false;
                    $rootScope.boolzc = false;
                    $rootScope.boolsjb = false;
                    break;
                case "sjb":
                    $rootScope.stylesjb = {'background-color': '#F07C2B', "color": "white"};
                    $rootScope.stylewd = {'background-color': ''};
                    $rootScope.stylezc = {'background-color': ''};
                    $rootScope.styleyhlc = {'background-color': ''};
                    $rootScope.styleall = {'background-color': '', "color": "#F07C2B"};
                    $rootScope.boolsjb = true;
                    $rootScope.boolwd = false;
                    $rootScope.boolyhlc = false;
                    $rootScope.boolzc = false;
                    break;
                default:
                    $rootScope.styleall = {'background-color': '#F07C2B', 'color': 'white'};
                    $rootScope.stylezc = {'background-color': ''};
                    $rootScope.stylewd = {'background-color': ''};
                    $rootScope.stylesjb = {'background-color': ''};
                    $rootScope.styleyhlc = {'background-color': ''};
                    $rootScope.boolwd = true;
                    $rootScope.boolzc = true;
                    $rootScope.boolyhlc = true;
                    $rootScope.boolsjb = true;
                    break;
            }
        }
        $scope.productszc = [];//众筹
        $scope.productswd = [];//网贷
        $scope.productsyhlc = [];//银行理财
        $scope.productssjb = [];//随机宝
        $scope.getListproductList = function () {
            productList.getProductList().success(function (result) {
                if (result.length != 0 && result != undefined) {
                    var length = result.length;
                    //console.log(result[1]["productCategoryCode"]);
                    for (var i = 0; i <= length; i++) {
                        if (result[i] != undefined) {
                            //if (result[i]["productCategoryCode"]== "zc") {
                            //    $scope.productszc.push(result[i]);
                            //}
                            if (result[i]["productCategoryCode"] == "wd") {
                                $scope.productswd.push(result[i]);
                            }
                            if (result[i]["productCategoryCode"] == "yhlc") {
                                $scope.productsyhlc.push(result[i]);
                            }
                            if (result[i]["productCategoryCode"] == "sjb") {
                                $scope.productssjb.push(result[i]);
                            }
                        }
                    }
                    console.log($scope.productsyhlc);
                    //console.log( $scope.productswd);
                }
            });
        }
        WMP.getProjectList($scope.page, $scope.roll)
            .success(function (ret) {

                if (ret.result == 0) {
                    $scope.total = ret.total;
                    if (ret.data != null) {
                        for (var i = 0; i < ret.data.length; i++) {
                            // ret.data[i].color = blockColor[$scope.projects.length % blockColor.length];
                            $scope.productszc.push(ret.data[i]);
                        }
                        if ($scope.productszc.length >= $scope.total) {
                            $scope.moreDataCanBeLoaded = false;
                        }
                        $scope.page += 1;
                        $scope.$broadcast('scroll.infiniteScrollComplete');
                        //console.log( $scope.productszc);
                    } else {
                        $scope.moreDataCanBeLoaded = false;
                    }
                } else {
                    Local.toast(ret.msg);
                }
            })
            .error(function (error) {
                $scope.moreDataCanBeLoaded = false;
                Local.toast("请重新登录");
                $state.go("login");
                if (error) {
                    console.log(error.message);
                }
            })
            .finally(function () {
                $scope.busy = false;
                $scope.$broadcast('scroll.refreshComplete');
            });
        $scope.gotozcDetail = function (id) {
            $state.go("product-zc-detail", {id: id});
        }
    })
    .controller('zcDetailCtrl', function ($scope, $state, $stateParams, $ionicHistory, Local, WMP, sharedProperties) {
        $scope.$on('$ionicView.enter', function (scopes, states) {
            console.log("into wmp detail");
        });
        $scope.selectTab = 0;
        WMP.getProjectDetail($stateParams.id)
            .success(function (ret) {
                if (ret.result == 0) {
                    $scope.project = ret.project;
                    $scope.pics = ret.pics;
                    $scope.team = ret.team;

                } else {
                    Local.toast(ret.msg);
                }
                console.log(ret);
            })
            .error(function (error) {
                Local.toast("请重新登录");
                $state.go("login");
                if (error) {
                    console.log(error.message);
                }
            });

        $scope.changeTab = function (ind) {
            $scope.selectTab = ind;
        };

        $scope.gotoWMPInvest = function (id) {
            //console.log(Local.username());
            if (undefined != Local.username()) {
                var can_fund = $scope.project.need_fund - $scope.project.has_fund;
                sharedProperties.setValue('project_name', $scope.project.project_name);
                sharedProperties.setValue('follow_fund', $scope.project.follow_fund);
                $state.go("wmp-invest", {id: id, can_fund: can_fund});
            }
            else {
                $state.go("login");
            }
        };

        $scope.goBack = function () {
            //$ionicHistory.goBack();
            $state.go("tab.dash");//返回列表首页
        };
    })
    .controller('ChoiceCtrl', function ($scope) {
    })
    .controller('ChatsCtrl', function ($scope, Chats) {
        // With the new view caching in Ionic, Controllers are only called
        // when they are recreated or on app start, instead of every page change.
        // To listen for when this page is active (for example, to refresh data),
        // listen for the $ionicView.enter event:
        //
        //$scope.$on('$ionicView.enter', function(e) {
        //});

        $scope.chats = Chats.all();
        $scope.remove = function (chat) {
            Chats.remove(chat);
        };
    })
    .controller('TabCtrl', function ($scope, $state, Local) {
        $scope.onTabSelected = function (_scope) {
            if (_scope.title === '我的') {
                if (undefined == Local.username()) {// unregistered
                    console.log("no local username, 1st use might be, when switch");
                    $state.go("login", {}, {reload: true});
                    return;
                }
            }
        }
    })

    .controller('ChatDetailCtrl', function ($scope, $stateParams, Chats) {
        $scope.chat = Chats.get($stateParams.chatId);
    })

    .controller('AccountCtrl', function ($scope, PersonalInfo, Port, Local, $state) {
        $scope.$on('$ionicView.enter', function (scopes, states) {
            // if(states.fromCache && states.stateName == "tab.dash"){
            console.log("refreshing Dash");
            $scope.getInfo();
            $scope.getUserAssets();


        });

        $scope.showMore = function (code) {
            Local.toast("敬请期待!");
            return true;
        }
        $scope.getUserAssets = function getUserAssets() {
            Port.getUserAssets()
                .success(function (custs) {
                    if (0 != custs.result) {
                        Local.toast("资产分布获取失败");
                    }
                    // success:
                    console.log(custs.result);
                    if (0 == custs.result) {
                        $scope.wd1 = custs.WDAmount;

                        $scope.yhlc1 = custs.YHLCAmount;
                        $scope.zc1 = custs.ZCAmount;
                        $scope.jnzh1 = custs.JNZHAmount;
                        $scope.kyyue1 = custs.KYAmount;
                        $scope.totalamount1 = custs.TotalAmount;
                        console.log(custs.WDAmount + "," + custs.ZCAmount + "," + custs.JNZHAmount + "," + custs.KYAmount + "," + custs.YHLCAmount);
                        var ctx = document.querySelector("#doughnut").getContext("2d");
                        if (($scope.totalamount1 + $scope.kyyue1) == 0) {
                            $scope.jnzh1 = 1;
                        }
                        var data = [
                            {
                                value: $scope.yhlc1,
                                color: "#01A0E8"
                            },
                            {
                                value: $scope.kyyue1,
                                color: "#BCBCBC"
                            },
                            {
                                value: $scope.zc1,
                                color: "#F29600"
                            },
                            {
                                value: $scope.jnzh1,
                                color: "#B28146"
                            },
                            {
                                value: $scope.wd1,
                                color: "#78BDFF"
                            }

                        ]
                        ctx.canvas.height = 200;
                        ctx.canvas.width = 200;
                        new Chart(ctx).Doughnut(data);

                    }
                })
                .error(function (error) {
                    Local.toast("请重新登录");
                    $state.go("login");

                    if (error)
                        console.log(error.message);
                });

            //环形图

        }
        $scope.getInfo = function getInfo() {

            if (undefined == Local.username()) {// unregistered
                console.log("no local username, 1st use might be");
                $state.go("login");
                return;
            }
            var inf = PersonalInfo.fetch();

            if (!inf) {
                Local.toast("网络故障");
                return;
            }
            inf.success(function (custs) {
                if (-1 == custs.result) {
                    Local.toast("查询暂不可用,请重新登录");
                    $state.go("login");
                }
                $scope.myinfo = custs;

                if (undefined == $scope.myinfo.yue) {
                    $scope.myinfo.yue = "0.00";
                    $scope.myinfo.dangqianbaozhengjin = "0.00";
                    $scope.myinfo.dangqianpeizie = "0.00";
                    $scope.myinfo.dangqianyingli = "0.00";
                    $scope.myinfo.leijibaozhengjin = "0.00";
                    $scope.myinfo.leijipeizie = "0.00";
                    $scope.myinfo.leijiyingli = "0.00";
                }

                $scope.isIdentifier = custs.is_shimingrenzheng;
                $scope.username = Local.username();
                PersonalInfo.realname = custs.shimingrenzheng;
                PersonalInfo.idcardcode = custs.shenfenzhenghao;
                PersonalInfo.setIdentifer(custs.is_shimingrenzheng);

            });
            inf.error(function (error) {
                Local.toast("请重新登录");
                $state.go("login");
                if (error)
                    console.log(error.message);
            });
            inf.finally(function () {
                // Stop the ion-refresher from spinning
                $scope.$broadcast('scroll.refreshComplete');
            });

            // update yue
            Port.queryUserAmount()
                .success(function (custs) {
                    if (-1 == custs.result) {
                        Local.toast("余额查询失败,请稍后重试");
                    }
                    // success:
                    console.log(custs.result);
                    if (0 == custs.result) {
                        console.log("total yue: " + custs.value);
                        $scope.account_yue = custs.value;
                    }
                })
                .error(function (error) {
                    Local.toast("请重新登录");
                    $state.go("login");

                    if (error)
                        console.log(error.message);
                });
        };
        $scope.isShowproperty = true;
        $scope.isShowearnings = false;
        $scope.stylePro = {'background-color': '#3399FF'};
        $scope.styleEarn = {'background-color': '#BCBCBC'};
        $scope.ShowProperty = function () {
            $scope.stylePro = {'background-color': '#3399FF'};
            $scope.styleEarn = {'background-color': '#BCBCBC'};
            $scope.isShowproperty = true;
            $scope.isShowearnings = false;
        }
        $scope.ShowEarnings = function () {
            $scope.stylePro = {'background-color': '#BCBCBC'};
            $scope.styleEarn = {'background-color': '#3399FF'};
            $scope.isShowproperty = false;
            $scope.isShowearnings = true;
        }


    })

    .controller('PropertyCtrl', function ($scope, $stateParams, Chats, Port, Local, $state) {

        $scope.$on('$ionicView.enter', function (scopes, states) {
            $scope.getUserAssets();
        });
        $scope.getUserAssets = function getUserAssets() {
            Port.getUserAssets()
                .success(function (custs) {
                    if (0 != custs.result) {
                        Local.toast("资产分布获取失败");
                    }
                    // success:
                    console.log(custs.result);
                    if (0 == custs.result) {
                        $scope.wd1 = custs.WDAmount;

                        $scope.yhlc1 = custs.YHLCAmount;
                        $scope.zc1 = custs.ZCAmount;
                        $scope.jnzh1 = custs.JNZHAmount;
                        $scope.kyyue1 = custs.KYAmount;
                        $scope.totalamount1 = custs.TotalAmount;
                        $scope.totalzc = $scope.totalamount1 + $scope.kyyue1;
                        if ($scope.totalzc == 0) {
                            $scope.jnzh1 = 1;
                        }
                        if ($scope.totalzc != 0) {
                            $scope.wdrate = ($scope.wd1 / $scope.totalzc * 100).toFixed(2);
                            $scope.yhlcrate = ($scope.yhlc1 / $scope.totalzc * 100).toFixed(2);
                            $scope.zcrate = ($scope.zc1 / $scope.totalzc * 100).toFixed(2);
                            $scope.jnzhrate = ($scope.jnzh1 / $scope.totalzc * 100).toFixed(2);
                            $scope.yuerate = ($scope.kyyue1 / $scope.totalzc * 100).toFixed(2);
                        }
                        else {
                            $scope.wdrate = 0;
                            $scope.yhlcrate = 0;
                            $scope.zcrate = 0;
                            $scope.jnzhrate = 0;
                            $scope.yuerate = 0;
                        }
                        //环形图
                        var ctx = document.querySelector("#subdoughnut").getContext("2d");
                        var data = [
                            {
                                value: $scope.yhlc1,
                                color: "#01A0E8"
                            },
                            {
                                value: $scope.kyyue1,
                                color: "#BCBCBC"
                            },
                            {
                                value: $scope.zc1,
                                color: "#F29600"
                            },
                            {
                                value: $scope.jnzh1,
                                color: "#B28146"
                            },
                            {
                                value: $scope.wd1,
                                color: "#78BDFF"
                            }

                        ]
                        ctx.canvas.height = 200;
                        ctx.canvas.width = 200;
                        new Chart(ctx).Doughnut(data);
                        //小环形图
                        var ctx = document.querySelector("#can1").getContext("2d");
                        var data = [
                            {
                                value: $scope.totalzc,
                                color: "#F8983E"
                            },
                            {
                                value: $scope.wd1,
                                color: "#78BDFF"
                            },

                        ]
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                        new Chart(ctx).Doughnut(data);
                        var ctx = document.querySelector("#can2").getContext("2d");
                        var data = [
                            {
                                value: $scope.yhlc1,
                                color: "#01A0E8"
                            },
                            {
                                value: $scope.totalzc,
                                color: "#F8983E"
                            },

                        ]
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                        new Chart(ctx).Doughnut(data);
                        var ctx = document.querySelector("#can3").getContext("2d");
                        var data = [
                            {
                                value: $scope.zc1,
                                color: "#F29600"
                            },
                            {
                                value: $scope.totalzc,
                                color: "#F8983E"
                            },

                        ]
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                        new Chart(ctx).Doughnut(data);
                        var ctx = document.querySelector("#can4").getContext("2d");
                        var data = [
                            {
                                value: $scope.jnzh1,
                                color: "#B28146"
                            },
                            {
                                value: $scope.totalzc,
                                color: "#F8983E"
                            },

                        ]
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                        new Chart(ctx).Doughnut(data);
                        var ctx = document.querySelector("#can5").getContext("2d");
                        var data = [
                            {
                                value: $scope.kyyue1,
                                color: "#BCBCBC"
                            },
                            {
                                value: $scope.totalzc,
                                color: "#F8983E"
                            },

                        ]
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                        new Chart(ctx).Doughnut(data);
                        ctx.canvas.height = 60;
                        ctx.canvas.width = 60;
                    }
                })
                .error(function (error) {
                    Local.toast("请重新登录");
                    $state.go("login");

                    if (error)
                        console.log(error.message);
                });

            //环形图

        }
        //返回资产
        $scope.goBackProperty = function () {
            $state.go("tab.account");
        }

    })
    .controller('EarningsCtrl', function ($scope) {

    })

    .controller('LoginCtrl', function ($rootScope, $scope, $http, $location, $state, PersonalInfo, NewPersonalInfo, Local, Port) {

        $scope.clearInput = function () {
            $scope.cellnumber = null;
        };
        $scope.service_offline = false;
        $scope.service_connected = true;

        $scope.goBack = function () {
            //$ionicHistory.goBack();
            $state.go("tab.dash");//返回列表首页
        };

        $scope.goBackdash = function () {
            $state.go("tab.dash");
        }
        $scope.tryLogin = function (phone, password) {
            $scope.service_connected = true;
            $scope.service_offline = false;
            $rootScope.$broadcast('loading:show');

            PersonalInfo.login(phone, password)
                .success(function (custs) {
                    var result = custs.result;
                    var token = custs.token;
                    if (0 == result) {
                        // 旧API登录成功后，登录新的API
                        NewPersonalInfo.login(phone, password)
                            .success(function (data) {
                                $rootScope.$broadcast('loading:hide');
                                var newApiResult = data.result;
                                var newApiToken = data.token;
                                if (newApiResult == 0) {
                                    // 新旧API都登录成功
                                    var storage = window.localStorage;
                                    Local.setUsername(phone);
                                    // 旧token
                                    Local.setToken(token);
                                    // 新token
                                    Local.setNewToken(newApiToken);
                                    $state.go("tab.dash");

                                } else if (result == -1) {
                                    Local.toast("用户名或密码错误");
                                    return;
                                }
                            })
                            .error(function (error) {
                                $rootScope.$broadcast('loading:hide');
                                Local.toast("网络故障");
                                if (error) {
                                    console.log(error.message);
                                }
                            });

                    } else if ("-1" == result) {
                        Local.toast("用户名或密码错误");
                        // $scope.login_failed = true;
                        return;
                    }
                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    // $scope.login_failed = true;
                    Local.toast("网络故障");
                    if (error) {
                        console.log(error.message);
                    }
                });
        };

        $scope.login_failed = false;
    })// .controller('LoginCtrl', function($scope) {

    .controller('ChargeCtrl', function ($scope, $rootScope, $state, Port, Local) {

        $scope.charge = function (jine_arg) {
            if (jine_arg == null) {
                Local.toast("充值金额不能为空");
                return;
            }
            if (parseFloat(jine_arg) <= 0) {
                Local.toast("充值金额应大于0,请重新填写");
                return;
            }

            Local.setPayType(0);
            var customerId = Local.username();
            Local.setToBePayObj(customerId, 0, 0, 0, jine_arg);
            // $state.go("tab.chargebanklist");
            $state.go("select-pay-bankcard");
        }
    })
    .controller('SelectPayBankCardCtrl', function ($scope, $rootScope, $state, Local, Port, NewPort, BankCards) {
        $scope.bankCards = [];
        $scope.$on('$ionicView.enter', function (scopes, states) {
            $scope.QueryUserBankCards();
        });

        $scope.QueryUserBankCards = function () {
            BankCards.queryBankCards()
                .success(function (ret) {
                    Local.toast('获取银行卡成功');
                    $scope.bankCards = [];
                    if (ret.result == 0) {
                        for (var i = 0; i < ret.cardlist.length; i++) {
                            $scope.bankCards.push(ret.cardlist[i]);
                        }
                    }
                })
                .error(function (ret) {
                    Local.toast(ret);
                });
        };
        $scope.FilterBankID = function (bankname) {
            var str = "";
            switch (bankname) {
                case "中国工商银行":
                    str = "ICBC_D_B2C";
                    break;
                case "中国农业银行":
                    str = "ABC_D_B2C";
                    break;
                case "中国建设银行":
                    str = "CCB_D_B2C";
                    break;
                case "民生银行":
                    str = "CMBCD_D_B2C";
                    break;
                case "中国银行":
                    str = "BOCSH_D_B2C";
                    break;
                case "兴业银行":
                    str = "CIB_D_B2C";
                    break;
                case "光大银行":
                    str = "CEB_D_B2C";
                    break;
                case "中信银行":
                    str = "CNCB_D_B2C";
                    break;
                case "平安银行":
                    str = "PINGAN_D_B2C";
                    break;
                case "中国邮政":
                    str = "POSTGC_D_B2C";
                    break;
                case "交通银行":
                    str = "COMM_D_B2C";
                    break;
                default :
                    str = "error"
                    break;
            }
            return str;
        }
        $scope.goBackCharge = function () {
            $state.go("tab.charge");
        };
        $scope.selectBankCard = function (o) {
            $rootScope.$broadcast('loading:show');
            if ($scope.FilterBankID(o.BankName) == "error") {
                Local.toast("不支持当前银行或者银行名称有误");
                return;
            }
            Local.setCertInfoObj(o.CardNumber, o.RealName, o.UserId, '01', $scope.FilterBankID(o.BankName), Local.username());

            Port.getSecurityCodeByBankCardId(o.Id, Local.getToBePayObj().to_be_charged, Local.getPayType(), $scope.FilterBankID(o.BankName))
                .success(function (ret) {
                    $rootScope.$broadcast('loading:hide');
                    if (ret.result == 0) {
                        Local.toast(ret.msg);
                        console.log("request security code log: " + ret.result);
                        Local.setSecurityCodeResult(ret.out_trade_no, "", ret.token, ret.sign);
                        // Local.toast("获取验证码请求已发送,请查收短信", 2500);
                        $state.go("readytopay");
                        //$state.go("tab.portfolio-log", {}, { reload: true });
                    } else {
                        console.log(ret.msg);
                        Local.toast("发送验证码失败！" + (ret.msg || ""));
                    }
                })
                .error(function (ret) {
                    $rootScope.$broadcast('loading:hide');
                    Local.toast(ret);
                });
        };

        $scope.useOtherBankCard = function () {
            $state.go("chargebanklist");
        };

    })

    .controller('AccVerifyCtrl', function ($scope, $rootScope, $state, Local, Port) {
        $scope.closeModal = function () {
            $state.go("tab.charge");
        };
        var bankObj = Local.getSelectedBank();
        var payObj = Local.getToBePayObj();
        var customerId = Local.username();

        $scope.log = {bank_name: bankObj.bank_name};
        $scope.verifyInfo = function (cardNo, realName, certNo, certType, phoneNo) {
            if (!cardNo) {
                Local.toast("卡号不能为空,请重新填写");
                return;
            }
            if (!realName) {
                Local.toast("姓名不能为空,请重新填写");
                return;
            }

            if (!certNo || (certType === "01" && certNo.length < 18)) {
                Local.toast("证件号不正确,请重新填写");
                return;
            }

            if (!certType) {
                certType = "01";
            }

            if (!phoneNo || !Local.isValidPhoneNumber(phoneNo)) {
                Local.toast("手机号输入不正确,请重新填写");
                return;
            }
            Local.setCertInfoObj(cardNo, realName, certNo, certType, bankObj.bank_id, phoneNo);

            Port.getSecurityCode(customerId, payObj.to_be_charged, cardNo, realName, certNo, certType, bankObj.bank_id, bankObj.bank_name, phoneNo, Local.getPayType())
                .success(function (custs) {
                    console.log("request security code log: " + custs.result);
                    if (0 == custs.result) {
                        Local.setSecurityCodeResult(custs.out_trade_no, "", custs.token, custs.sign);
                        Local.toast("获取验证码请求已发送,请查收短信", 2500);
                        $state.go("readytopay");
                        //$state.go("tab.portfolio-log", {}, { reload: true });
                    } else {
                        Local.toast("请稍候重试," + custs.msg);
                    }
                })
                .error(function (error) {
                    Local.toast("网络故障:" + error.message);
                    if (error)
                        console.log(error.message);
                });
        };
    })
    .controller('BankListChooseCtrl', function ($scope, $rootScope, $ionicHistory, $state, Local, Port) {
        var bankList = Local.getBankList();
        var obj = Local.getToBePayObj();
        $scope.log = {to_be_charged: obj.to_be_charged, bank_list: bankList};
        $scope.closeModal = function () {
            $ionicHistory.goBack();
        };
        $scope.setBankID = function (bankId, bankName) {
            Local.setSelectedBank(bankId, bankName);
            var money = obj.to_be_charged;

            console.log(money, bankId, bankName);
            if (!money || parseFloat(money) <= 0) {
                Local.toast("充值金额应大于0,请重新填写");
                return;
            }
            $state.go("accountverification");
        };
        $scope.submit = function (money, choseBank) {
            //tempraryly removed submit button
        };
    })
    .controller('ReadyToPayCtrl', function ($scope, $rootScope, $state, Local, Port) {
        var bankObj = Local.getSelectedBank();
        var moneyObj = Local.getToBePayObj();
        var accObj = Local.getCertInfoObj();
        var securityCodeObj = Local.getSecurityCodeResult();

        $scope.log = {totalFee: moneyObj.to_be_charged};
        $scope.closeModal = function () {
            $state.go("tab.charge");
        };

        $scope.submit = function (money, verifyCode) {
            if (!verifyCode) {
                Local.toast("请输入正确的验证码");
                return;
            }

            //调用认证支付接口
            $rootScope.$broadcast('loading:show');

            Port.userChargeBeifu(money, verifyCode, securityCodeObj.security_code_token, securityCodeObj.out_trade_no,
                moneyObj.customer_Id, accObj.card_no, accObj.real_name, accObj.cert_no, accObj.cert_type,
                bankObj.bank_id, accObj.bind_phone_no, securityCodeObj.signKey)
                .success(function (custs) {
                    $rootScope.$broadcast('loading:hide');
                    Local.toast(custs.msg);
                    console.log(custs.msg);
                    // success:
                    console.log(custs.result);
                    if (0 === custs.result) {
                        var respData = custs.response_data;
                        Local.toast(custs.msg);
                        console.log("after charge the response_data is: " + respData);
                        //window.open(url, '_system');
                        setTimeout(function () {
                            $state.go("tab.account");
                        }, 1000);
                    }
                    else {
                        Local.toast("支付失败!");
                    }
                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    Local.toast(error);
                    if (error)
                        console.log(error.message);
                });
        };
    })

    .controller('WithdrawCtrl', function ($scope, $rootScope, $ionicPopup, $state, Port, Local, BankCards, PersonalInfo) {

        $scope.isDetailWithdraw = false;
        $scope.isWithdraw = false;
        //$scope.withdrawInfo={AccountName:"-",Amount:"-",BankType:"-",BankCardNo:"-",BankCardDesc:"-",Status:"-"};


        //提现时必须先实名认证
        $scope.showForceIdentiferDialog = function () {
            $ionicPopup.show({
                title: '提示信息',
                template: '请先进行实名认证,然后才能进行提现!',
                scope: $scope,
                buttons: [
                    {
                        text: '暂不认证',
                        onTap: function (e) {
                            $state.go("tab.dash");
                        }
                    },
                    {
                        text: '<b>去实名认证</b>',
                        class: 'button-assertive',
                        onTap: function (e) {
                            $state.go("identifier-bind");
                        }
                    },
                ]
            });
        }

        $scope.$on('$ionicView.enter', function (scopes, states) {

            $scope.bankCards = [];

            Port.getWithdrawInfo().success(function (custs) {
                if (custs.value != null) {
                    // 有提现申请，跳到申请列表页面
                    console.log(custs);
                    $scope.withdrawInfo = custs.value;
                    $scope.isDetailWithdraw = true;
                    $scope.isWithdraw = false;
                    //$state.go("tab.withdraw-detail");
                } else {
                    // 没有提现申请，进入申请页面
                    $scope.isDetailWithdraw = false;
                    $scope.isWithdraw = true;

                    if (!PersonalInfo.getIdentifer()) {
                        $scope.showForceIdentiferDialog();
                    }

                    BankCards.queryBankCards()
                        .success(function (ret) {
                            if (ret.result == 0) {
                                $scope.bankCards = [];
                                for (var i = 0; i < ret.cardlist.length; i++) {
                                    var item = ret.cardlist[i];
                                    item.Title = getCardName(item);
                                    $scope.bankCards.push(item);
                                    if (item.IsDefaultCard) {
                                        $scope.selectedCard = item;
                                    }
                                }
                            } else {
                                Local.toast(ret.msg)
                            }
                        })
                }
            }).error(function (error) {
                Local.toast("查询提现申请失败，请检查网络");
                $state.go("tab.dash");
                if (error) {
                    console.log(error.message);
                }
            });
        });

        $scope.type = 2;
        $scope.withdraw = function (sum, xingming, account, memo, type) {
            if (parseFloat(sum) <= 0) {
                Local.toast("金额应大于0,请重新填写");
                return;
            }
            if (!$scope.selectedCard || !$scope.selectedCard.CardNumber) {
                Local.toast("请设置提现银行卡！");
                return;
            }
            if (undefined == xingming) {
                Local.toast("姓名是必填项");
                return;
            }
            if (undefined == account) {
                Local.toast("账户是必填项");
                return;
            }
            $rootScope.$broadcast('loading:show');

            Port.userWithdraw(sum, xingming, account, memo, type)
                .success(function (custs) {
                    $rootScope.$broadcast('loading:hide');
                    if (-1 == custs.result) {
                        Local.toast("提现失败");
                    } else if (-2 == custs.result) {
                        Local.toast("账户余额不足，无法提现!");
                    } else if (-3 == custs.result) {
                        Local.toast("已存在申请中的提现申请，无法重复申请！");
                    }
                    // success:
                    console.log(custs.result);
                    if (0 == custs.result) {
                        Local.toast("提现请求发送成功");
                        setTimeout(function () {
                            $state.go("tab.dash");
                        }, 2000);
                    }

                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    Local.toast("请重新登录");
                    $state.go("login");

                    if (error)
                        console.log(error.message);
                });

        };

        var getCardName = function (card) {
            return card.BankName + " " + card.CardNumber.substring(0, 4) + "***" + card.CardNumber.substring(card.CardNumber.length - 4) + " " + card.RealName;
        };

        $scope.changeCard = function () {
            var cardNumber = this.selectedCard.CardNumber;
            for (var i = 0; i < $scope.bankCards.length; i++) {
                var item = $scope.bankCards[i];
                if (item.CardNumber == cardNumber) {
                    $scope.selectedCard = item;
                }
            }
        }
    })

    .controller("identifierBindCtrl", function ($scope, $state, $ionicPopover, $rootScope, $ionicPlatform, $location, $timeout, Local, Port, BankCards, PersonalInfo) {

        $scope.identifierInfo = {realname: "", idcardcode: ""};
        $scope.isIdentifier = PersonalInfo.getIdentifer();
        if ($scope.isIdentifier) {
            $scope.identifierInfo.realname = PersonalInfo.realname;
            $scope.identifierInfo.idcardcode = PersonalInfo.idcardcode;
        }

        $scope.submitIdentifierBind = function (realname, idcardcode) {

            BankCards.identifier_bind(realname, idcardcode)
                .success(function (ret) {
                    if (ret.result == 0) {
                        Local.toast(ret.msg);
                        $state.go("tab.dash")
                    } else {
                        Local.toast(ret.msg);
                    }
                })
                .error(function (ret) {
                    Local.toast(reg.msg);
                });
        };

    })

    .controller('ProductDetailCtrl', function ($scope, $state, Local, ProductService, mySettings) {

        $scope.productId = Local.getItem("select-productId");
        $scope.productType = Local.getItem("select-productType");

        console.log($scope.productId + "," + $scope.productType);
        //var ifm= document.getElementById("product-detail-iframe");
        //ifm.src=Local.getItem("select-productUrl");

        //{"Id":1,"ProductName":"一铜天下458期","ProductContent":"海南航空股份有限公司作为航空器出租人，将航空器(飞机)出租给航空公司，并将形成的应收租金转让给鑫银国际商业保理有限公司。航空公司以其机票销售回款作为还款来源。本产品对应山东金融资产交易中心<鲁金惠融财富·鑫银三十四期>产品。\r\n\r\n\r\n流程说明：\r\n（1）海南航空股份有限公司出租航空器给航空公司；\r\n（2）海南航空股份有限公司对航空公司形成应收租金；\r\n（3）海南航空向保理公司申请保理业务,并将应收租金转让给保理公司；\r\n（4）航空公司（债务人）以其机票销售回款支付租金。","ProductCategory":"网贷","ProductFrom":"铜板街","PlanEarning":"6.30","InvestEndDate":"28天","InvestStartMoney":100.00,"InvestPeopleNumber":652,"InvestSurplus":4343900.00,"StartAccrualDate":"2015-07-21 00-00-00","EndAccrualDate":"2015-08-18 00-00-00","ProductUrl":null,"result":1,"msg":null,"is_show_msg":false}
        $scope.product = {};
        $scope.$on('$ionicView.enter', function (scopes, states) {

            ProductService.GetProductDetail($scope.productId, $scope.productType).success(function (d) {
                if (d.result == 0) {
                    //document.getElementById("the-image-id").style.backgroundImage = "url('http://pic.miercn.com/uploads/allimg/150720/40-150H0094102.jpg')";
                    document.getElementById("the-image-id").style.backgroundImage = "url('http://rich.online.sh.cn/rich/gb/content/attachement/jpg/site1/20140423/0025116ac85d14c15c0c26.jpg')";
                    $scope.product = d;
                    mySettings.product = d;
                }
                if (d.msg) {
                    Local.toast(d.msg);
                }
            }).error(function (d) {
                Local.toast(d);
            });
            //$scope.PictureUrl="http://pic.miercn.com/uploads/allimg/150720/40-150H0094102.jpg";


        });

        //function iFrameHeight() {
        //    var subWeb = document.frames ? document.frames["product-detail-iframe"].document : ifm.contentDocument;
        //    var det = document.getElementById("detail-content");
        //    if(ifm != null && det != null) {
        //        ifm.height = (det.scrollHeight||det.height||det.clientHeight||det.offsetHeight)-30;
        //    }
        //};
        //iFrameHeight();
        $scope.gotoBuyProduct = function (id, type) {
            //$state.go("buy-product", {id: id});
            if (undefined != Local.username()) {
                $state.go("tab.buy-product", {id: id, type: type});
            }
            else {
                $state.go("login");
            }
        };
    })

// 聚募确认投资
    .controller("wmpInvestCtrl", function ($scope, $state, $stateParams, $ionicHistory, Local, NewPort, ProductService, mySettings) {
        $scope.$on('$ionicView.enter', function (scopes, states) {
            console.log("into wmp invest");
        });

        $scope.id = $stateParams.id;
        $scope.type = $stateParams.type;
        if ($scope.type == 1) {
            $scope.name = mySettings.product.ProductName;
            $scope.follow_fund = mySettings.product.InvestStartMoney;
        } else if ($scope.type == 2) {
            $scope.name = mySettings.product.ProjectName;
            $scope.follow_fund = mySettings.product.SalesAccount;
        }

        $scope.submitInvest = function (id, name, amount) {
            if (!$scope.checkAmount(amount)) {
                return;
            }

            if ($stateParams.type) {
                ProductService.AddProductOrder(amount, id, $scope.type, "")
                    .success(function (d) {
                        if (d.result == 0) {
                            Local.toast(d.value);
                            $state.go("tab.dash");
                        } else {
                            Local.toast(d.value);
                        }
                    })
                    .error(function (error) {
                        Local.toast("投资失败，请稍候重试！");
                        if (error) {
                            console.log(error.message);
                        }
                    });
            } else {
                NewPort.ProjectInvest(id, name, amount)
                    .success(function (ret) {
                        if (ret.result == 0) {
                            console.log(ret);
                            Local.toast(ret.msg);
                            $state.go("tab.dash");
                        } else {
                            Local.toast(ret.msg);
                        }
                    })
                    .error(function (error) {
                        Local.toast("投资失败，请稍候重试！");
                        if (error) {
                            console.log(error.message);
                        }
                    });
            }
        };

        $scope.checkAmount = function (amount) {
            amount = parseInt(amount);
            if (isNaN(amount)) {
                Local.toast("请输入数字。");
                return false;
            }
            //if (amount < 1000) {
            //    Local.toast("投资金额不能小于1000元。");
            //    return false;
            //}

            if (amount < $scope.follow_fund) {
                Local.toast("本项目最低投资金额为" + $scope.follow_fund + "元。");
                return false;
            }

            if (amount % 100 != 0) {
                Local.toast("投资金额必须是100元的整倍数。");
                return false;
            }

            return true;
        }

        $scope.goBacktoDetail = function (id) {
            //$ionicHistory.goBack();
            $state.go("product-zc-detail", {id: id});
        };
    })
    .controller('SignupCtrl', function ($rootScope, $scope, $state, $ionicModal, $ionicHistory, $timeout, $interval, Local, PersonalInfo) {
        $scope.goBack = function () {
            $ionicHistory.goBack();
        };

        $scope.signup_failed = false;
        $scope.duplicated = false;
        $scope.auth_code_sent = false;

        $scope.clearInput = function () {
            $scope.cellnumber = null;
        };


        var storage = window.localStorage;

        // count down button:auth_code
        $scope.btn_text = "获取验证码";

        var countdown;
        var countdown_seconds;

        function stopCountdown() {
            if (angular.isDefined(countdown)) {
                console.log("count down stopping");
                $interval.cancel(countdown);
                $scope.btn_text = "获取验证码";
                countdown = undefined;
                return;
            }
        }

        function startCountDown(duration) {
            if (angular.isDefined(countdown)) {
                console.log("count down start already started");
                return;
            }
            countdown_seconds = 60;
            countdown = $interval(function () {
                $scope.btn_text = countdown_seconds + "秒后重发";
                if (countdown_seconds > 0)
                    countdown_seconds -= 1;
            }, 1000);

            $timeout(stopCountdown, 60000);
        }

        $scope.$on('$destroy', function () {
            stopCountdown();
        });

        $scope.getAuthCode = function (phone) {
            if (!Local.isValidPhoneNumber(phone)) {
                Local.toast("请输入有效手机号!");
                return;
            }
            if (countdown) {
                Local.toast("请倒计时结束后再重发验证码");
                return;
            }

            $rootScope.$broadcast('loading:show');
            PersonalInfo.auth_code_register(phone)
                .success(function (custs) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.auth_code_sent = true;
                    if (custs.result == 0) {
                        Local.toast("验证码已发送到: " + phone);
                        startCountDown();
                    } else if (custs.result == -2) {
                        Local.toast("手机号已经注册，如果忘记密码请找回");
                    } else {
                        Local.toast("验证码发送失败,请稍后重试");
                    }

                    // $scope.openModal();
                    console.log("got auth code" + custs.result);
                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.signup_failed = true;
                    Local.toast("网络故障");
                    if (error)
                        console.log(error.message);
                });

        };


        $scope.step2 = function (phone, code) {
            if (!Local.isValidPhoneNumber(phone)) {
                Local.toast("请输入有效手机号!");
                return;
            }
            if (!code) {
                Local.toast("请输入验证码!");
                return;
            }

            $rootScope.$broadcast('loading:show');
            PersonalInfo.auth_code_check(phone, code)
                .success(function (custs) {
                    $rootScope.$broadcast('loading:hide');
                    if (custs.result != 0) {
                        Local.toast("验证码不正确");
                        return;
                    } else {
                        $scope.auth_code = code;
                        $scope.cellnumber = phone;
                        $scope.openModal();
                    }
                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.signup_failed = true;
                    Local.toast("网络故障");
                    if (error) {
                        console.log(error.message);
                    }
                    return;
                });
        };


        $ionicModal.fromTemplateUrl('templates/signup-2.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.modal = modal;
        });

        $scope.openModal = function () {

            $scope.modal.show();
        };

        $scope.closeModal = function () {
            $scope.modal.hide();
        };

        $scope.$on('$destroy', function () {
            $scope.modal.remove();
        });


        $scope.trySignup = function (phone, password, password_re, auth_code, nick_name, invite_code) {

            if (password != password_re) {
                Local.toast("两次输入的密码不一致");
                return;
            }
            if (String(password).length > 20 || String(password).length < 6) {
                Local.toast("密码长度请控制在6-20位之间");
                return;
            }

            $rootScope.$broadcast('loading:show');
            $scope.service_connected = true;
            $scope.service_offline = false;

            PersonalInfo.register(phone, password, auth_code, nick_name, invite_code)
                .success(function (custs) {
                    $rootScope.$broadcast('loading:hide');
                    var result = custs.result;
                    var token = custs.token;
                    if ("0" == result || 0 == result) {
                        var storage = window.localStorage;
                        storage.setItem("username", phone);
                        storage.setItem("token", token);
                        console.log("token: " + token + " set for " + phone);
                        $scope.closeModal();
                        $state.go("tab.dash");
                    } else if (-1 == result) {
                        Local.toast("该用户名已经被占用");
                    } else if (-2 == result) {
                        Local.toast("验证码不正确");
                    }
                })
                .error(function (error) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.signup_failed = true;
                    Local.toast("网络故障");
                    if (error)
                        console.log(error.message);
                });


        };

    }) // .controller('SignupCtrl', function($scope) {
    .controller('BillCtrl', function ($scope, $rootScope, $state, Port, Local) {

        $scope.moreDataCanBeLoaded = true;

        $scope.start = 1;
        $scope.pagecapacity = 10;
        $scope.bills = [];

        $scope.$on('$ionicView.enter', function (scopes, states) {
            // if(states.fromCache && states.stateName == "tab.dash"){
            console.log("refreshing bill");
            // $scope.bill();
            // }
        });

        $scope.$on('$stateChangeSuccess', function () {
            console.log("usging start: " + $scope.start);
            $scope.bill();
        });
        $scope.bill = function () {
            // $rootScope.$broadcast('loading:show');
            if ($scope.busy) {
                console.log("busy, returning");
                return;
            }

            $scope.busy = true;

            Port.queryUserBills($scope.start, $scope.pagecapacity)
                .success(function (custs) {
                    // $rootScope.$broadcast('loading:hide');
                    if (-1 == custs.result) {
                        Local.toast("查询失败");
                    }
                    // success:
                    if (custs.value) {
                        if (0 == custs.result) {
                            for (var i = 0; i < custs.value.length; i++) {
                                $scope.bills.push(custs.value[i]);
                            }
                        }
                        $scope.$broadcast('scroll.infiniteScrollComplete');
                        if (custs.value.length < $scope.pagecapacity) {
                            console.log("No more data can be loaded");
                            $scope.moreDataCanBeLoaded = false;
                        }

                        if (0 < $scope.bills.length) {
                            $scope.start = $scope.bills.length + 1;
                            // console.log("setting start to: "+$scope.start);
                        }
                    } else {
                        console.log("No more data loaded");
                        $scope.moreDataCanBeLoaded = false;
                    }

                })
                .error(function (error) {
                    // $rootScope.$broadcast('loading:hide');
                    $scope.moreDataCanBeLoaded = false;
                    Local.toast("请重新登录");
                    $state.go("login");

                    if (error)
                        console.log(error.message);
                }).finally(function () {
                    $scope.busy = false;
                    // Stop the ion-refresher from spinning
                    $scope.$broadcast('scroll.refreshComplete');
                });

        };
    })

    .filter('withdrawBankType', function () {
        var sFilter = function (input) {
            var str = "";
            switch (input) {
                case 1:
                    str = "支付宝";
                    break;
                case 2:
                    str = "银行卡";
                    break;
            }
            return str;
        };
        return sFilter;
    })

    .filter('withdrawStatus', function () {
        var sFilter = function (input) {
            var str = "";
            switch (input) {
                case 0:
                    str = "提现申请中";
                    break;
                case 1:
                    str = "提现通过";
                    break;
                case 2:
                    str = "拒绝提现";
                    break;
            }
            return str;
        };
        return sFilter;
    })

    .directive('elasticImage', function ($ionicScrollDelegate) {
        return {
            restrict: 'A',
            link: function ($scope, $scroller, $attr) {
                var image = document.getElementById($attr.elasticImage);
                var center = document.getElementById($attr.elasticImage);
                var imageHeight = image.offsetHeight;

                $scroller.bind('scroll', function (e) {
                    var scrollTop = e.detail.scrollTop;
                    var newImageHeight = imageHeight - scrollTop;
                    if (newImageHeight < 0) {
                        newImageHeight = 0;
                    }
                    image.style.height = newImageHeight + 'px';
                });
            }
        }
    })
    .filter('pzColor', function () {
        var sFilter = function (input) {
            if (parseFloat(input) > 0) {
                return 'green';
            } else
                return 'red';

        };
        return sFilter;
    })

